package com.itron.base.filter;

import com.alibaba.fastjson.JSONObject;
import org.springframework.context.annotation.Configuration;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * token的过滤器
 */
@Configuration
@WebFilter
public class TokenFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse res = (HttpServletResponse) servletResponse;
        ServletRequest requestWrapper = null;
        try {
            requestWrapper = new MAPIHttpServletRequestWrapper(req);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String  token = requestWrapper.getParameter("token");
        System.out.println(token);
        if (token != null &&token.length()>0) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            responseData(servletResponse, res);
        }
    }

    @Override
    public void destroy() {
    }

    /**
     * 错误时返回403 信息
     *
     * @param response
     * @param res
     * @throws IOException
     */
    private void responseData(ServletResponse response, HttpServletResponse res) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = null;
        try {
            JSONObject obj = new JSONObject();
            obj.put("code", "403");
            obj.put("msg", "token is error");
            out = res.getWriter();
            out.append(obj.toString());
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
            res.sendError(500);
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

}
